<?php

namespace App\Api\Services;

use App\Api\Models\LogPackageContentModel;
use App\Api\Models\LogPackageModel;
use App\Api\Models\MaterielTypeModel;
use App\Api\Models\PackageContentModel;
use App\Api\Models\PackageModel;
use App\Api\Models\SalesReturnInPackageContentModel;
use App\Api\Models\SalesReturnInPackageModel;
use App\Api\Models\SalesReturnInStorageModel;
use App\Api\Models\SalesReturnPackageContentModel;
use App\Api\Models\SalesReturnPackageModel;
use App\Api\Models\StorageManageModel;
use App\Api\Models\StorageModel;
use App\Models\SalesReturnGoodsDetailModel;
use App\Models\SalesReturnModel;
use App\Models\SalesReturnPayRecordModel;
use App\Api\Services\StorageManageService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class SalesReturnService
{
    //新建
    static public function add($mainInfo, $data)
    {
        DB::beginTransaction();

        $mainId = SalesReturnModel::insertGetId($mainInfo);//创建销售主单信息
        $money = 0;//货款金额

        try {
            $salesMaterielInfo = [];
            $salesPackageInfo = [];

            if(!empty($data['goods_info'])) {
                $goodsInfo = json_decode($data['goods_info'],true);//商品详细添加

                foreach ($goodsInfo as $key => $value) {
                    $money+=($value['price']*$value['num']);
                    $materielInfo  = MaterielTypeModel::where('id', $value['materiel_type_id'])->first();
                    $storageInfo = StorageModel::where('id', $value['warehouse_id'])->first();
                    $salesMaterielInfo[$key]['materiel_type_id'] = $value['materiel_type_id'];
//                    $salesMaterielInfo[$key]['remark'] = $value['remark'];
                    $salesMaterielInfo[$key]['name'] = $materielInfo['materiel_name'];
                    $salesMaterielInfo[$key]['type_name'] = $materielInfo['type_name'];
                    $salesMaterielInfo[$key]['price'] = $value['price'];
                    $salesMaterielInfo[$key]['cost_price'] = $materielInfo['cost'];
                    $salesMaterielInfo[$key]['return_id'] = $mainId;
                    $salesMaterielInfo[$key]['num'] = $value['num'];
                    $salesMaterielInfo[$key]['image'] = $materielInfo['materiel_img'];
                    $salesMaterielInfo[$key]['warehouse_id'] = $storageInfo['id'];
                    $salesMaterielInfo[$key]['warehouse'] = $storageInfo['storage_name'];
                    $salesMaterielInfo[$key]['main_id'] = $data['main_id'];
                    $salesMaterielInfo[$key]['created_at'] = time();
                }

                SalesReturnGoodsDetailModel::insert($salesMaterielInfo);
            }

            if(!empty($data['package_info'])) {
                $packageInfo = json_decode($data['package_info'],true);//套餐信息
                foreach ($packageInfo as $k => $vals) {
                    $money+=($vals['price']*$vals['num']);
                    $salesPackageInfo[$k]['package_id'] = $vals['package_id'];
                    $salesPackageInfo[$k]['price'] = $vals['price'];
                    $salesPackageInfo[$k]['cost_price'] = SELF::getPackageCost($vals['package_id']);
                    $salesPackageInfo[$k]['num'] = $vals['num'];
                    $salesPackageInfo[$k]['main_id'] = $data['main_id'];
                    $salesPackageInfo[$k]['return_id'] = $mainId;
//                    $salesPackageInfo[$k]['remark'] = $vals['remark'];
                    $salesPackageInfo[$k]['created_at'] = time();
                    $salesPackageInfo[$k]['package_content'] = $vals['package_content'];
                }

                $packageContentInfo = [];
                foreach($salesPackageInfo as $val) {
                    $newId = SalesReturnPackageModel::insertGetId([
                        'package_id' => $val['package_id'],
                        'price' => $val['price'],
                        'cost_price' => $val['cost_price'],
                        'num' => $val['num'],
                        'main_id' => $val['main_id'],
                        'return_id' => $val['return_id'],
//                        'remark' => $val['remark'],
                        'created_at' => time()
                    ]);

                    foreach($val['package_content'] as $v) {
                        $packageContentInfo[] = [
                            'type_id' => $v['type_id'],
                            'storage_id' => $v['storage_id'],
                            'package_content_id' => $v['id'],
                            'storage_manage_id' => $v['storage_manage_id'],
                            'return_package_id' => $newId,
                            'package_id' => $val['package_id'],
                            'num' => $v['num'],
                            'main_id' => $data['main_id'],
                            'return_id' => $mainId,
                            'created_at' => time(),
                        ];
                    }
                }

                SalesReturnPackageContentModel::insert($packageContentInfo);
            }

            //非改价计算价格
            if(!$data['is_zero_suppression'] && $money){
                $finalMoney = 0;
                if(isset($data['discount']) && $data['discount']){//折扣
                    $finalMoney+= ($data['discount']*$money/100);
                }else{
                    $finalMoney = $money;
                }

                if(isset($data['tax_rate']) && $data['tax_rate']){//加税点
                    $finalMoney+= ($data['tax_rate']*$finalMoney/100);
                }
                SalesReturnModel::where('id',$mainId)->update(['final_money'=>$finalMoney,'money'=>$money]);
            }else{
                SalesReturnModel::where('id',$mainId)->update(['money'=>$money]);
            }

            DB::commit();//提交事务
            return ['code' => 0, 'msg' => 'success', 'data' => $mainId];
        }
        catch(\Exception $e) {
            DB::rollBack();//事务回滚
            Log::debug('添加退货单'.var_export($e->getMessage(), true));
            //异常响应
            return ['code' => 1, 'msg' => $e->getMessage(), 'data' => ''];
        }
    }

    //获取套餐总成本
    static private function getPackageCost($packageId)
    {
        $packageTotalCost = PackageContentModel::select(
            'a.num',
            'b.materiel_mean_cost'
        )
            ->from('package_content as a')
            ->leftJoin('storage_manage as b', 'b.id', '=', 'a.storage_manage_id')
            ->where('a.package_id', $packageId)
            ->where('a.delete_flag', 0)
            ->where('b.delete_flag', 0)
            ->first();

        return $packageTotalCost['num'] * $packageTotalCost['materiel_mean_cost'];
    }

    //详细
    static public function find($id)
    {
        $result = SalesReturnModel::select('a.*','b.username',
            'b.nickname'
        )
            ->from('sales_return as a')
            ->leftJoin('admin as b', 'b.id', '=', 'a.user_id')
        ->with('returnMateriel')
            ->with('returnPackage', function($query) {
                $query->select(
                    'sales_return_package.*',
                    'b.package_name'
                )
                    ->with('packageContent',function($query) {
                        $query->select(
                            'sales_return_package_content.*',
                            'a.materiel_name',
                            'a.type_name',
                            'b.storage_name',
                            'b.storage_address',
                            'c.in_storage_num',
                            'a.materiel_no',
                            'd.id as materiel_class_id',
                            'd.class_name'
                        )
                            ->leftJoin('materiel_type as a', 'a.id', '=', 'sales_return_package_content.type_id')
                            ->leftJoin('storage as b', 'b.id', '=', 'sales_return_package_content.storage_id')
                            ->leftJoin('storage_manage as c', 'c.id', '=', 'sales_return_package_content.storage_manage_id')
                            ->leftJoin('materiel_class as d', 'd.id', '=', 'a.materiel_class_id');
                    })
                    ->leftJoin('package as b', 'b.id', '=', 'sales_return_package.package_id');
            })
            ->where('a.id', $id)->first()->toArray();

        foreach($result['return_materiel'] as &$value) {
            $materielInfo = MaterielTypeModel::where('id', $value['materiel_type_id'])->first();

            $storageManageInfo = StorageManageModel::where('type_id', $value['materiel_type_id'])
                ->where('storage_id', $value['warehouse_id'])->first();

            $value['storage_manage_id'] = $storageManageInfo['id'];
            $value['materiel_class_id'] = $storageManageInfo['materiel_class_id'];
            $value['in_storage_num'] = $storageManageInfo['in_storage_num'];

            $value['image'] = $materielInfo['materiel_img'];
            $value['materiel_no'] = $materielInfo['materiel_no'];
        }

        return ['code' => 0, 'msg' => 'success','data' => $result];
    }

    //编辑
    static public function edit($mainInfo, $data)
    {
//        if (isset($mainInfo['refund_date'])) $mainInfo['refund_date'] = strtotime($data['refund_date']);

        $money = 0;

        DB::beginTransaction();

        try {
            if(!empty($data['goods_info'])) {
                SalesReturnGoodsDetailModel::where('return_id', $data['id'])->delete();
                $goodsInfo = json_decode($data['goods_info'], true);

                foreach ($goodsInfo as $key => $value) {
                    $money += ($value['price']*$value['num']);
                    $goods = SalesReturnGoodsDetailModel::where(['return_id'=>$data['id'],'materiel_type_id'=>$value['materiel_type_id']])->first();

                    $materielInfo = MaterielTypeModel::where('id', $value['materiel_type_id'])->first();
                    $storageInfo = StorageModel::where('id', $value['warehouse_id'])->first();

                    $value['name'] = $materielInfo['materiel_name'];
                    $value['type_name'] = $materielInfo['type_name'];
                    $value['materiel_no'] = $materielInfo['materiel_no'];
                    $value['image'] = $materielInfo['materiel_image'];
                    $value['warehouse'] = $storageInfo['storage_name'];

                    //更新
                    if($goods){
                        SalesReturnGoodsDetailModel::where(['return_id'=>$data['id'],'materiel_type_id'=>$value['materiel_type_id']])->update($value);
                    }else{//添加
                        $value['main_id'] = $data['main_id'];
                        $value['return_id'] = $data['id'];
                        $value['created_at'] = time();
                        SalesReturnGoodsDetailModel::insert($value);
                    }
                }
            }

            if(!empty($data['package_info'])) {
                $packageInfo = json_decode($data['package_info'], true);
                $packageContentInfo = [];
                SalesReturnPackageModel::where(['return_id'=>$data['id']])->delete();
                SalesReturnPackageContentModel::where(['return_id'=>$data['id']])->delete();

                foreach($packageInfo as $val) {
                    $packageId = SalesReturnPackageModel::insertGetId([
                            'package_id' => $val['package_id'],
                            'price' => $val['price'],
                            'cost_price' => SELF::getPackageCost($val['package_id']),
                            'num' => $val['num'],
//                            'remark' => $val['remark'],
                            'main_id' => $data['main_id'],
                            'return_id' => $data['id'],
                            'created_at' => time()
                        ]);

                        foreach($val['package_content'] as $k => $v) {
                            $packageContentInfo[] = [
                                'type_id' => $v['type_id'],
                                'storage_id' => $v['storage_id'],
                                'package_content_id' => $v['id'],
                                'storage_manage_id' => $v['storage_manage_id'],
                                'return_package_id' => $packageId,
                                'num' => $v['num'],
                                'main_id' => $data['main_id'],
                                'return_id' => $data['id'],
                                'created_at' => time()
                            ];
                        }
                }

                SalesReturnPackageContentModel::insert($packageContentInfo);
            }
            $srData = array();

            $param  = [
                        'customer_name','discount','tax_rate',
                        'proof_image','final_money','real_money','remark',
                        'out_order_no','refund_date','is_zero_suppression'
                      ];

           foreach ($data as $k=>$v){

               if(in_array($k,$param)){

                   $srData[$k]=$v;
               }
           }

            SalesReturnModel::where(['id'=>$data['id']])->update($srData);

            DB::commit();
            return ['code' => 0, 'msg' => 'success', 'data' => ''];
        }
        catch(\Exception $e) {
            DB::rollBack();
            Log::debug('修改退货单异常:'.var_export($e->getMessage(), true));
            return ['code' => 1, 'msg' => $e->getMessage(), 'data' => ''];
        }
    }

    static public function in($data)
    {
        $info = SalesReturnModel::where('id',$data['id'])->first();

        if($info['out_status'] == 2) {
            return ['code' => 1, 'msg' => '退货单已全部入库，无法重复操作', 'data' => ''];
        }

        $paramsArr = [];//出入库参数
        $paramsArr['in_storage_time'] = $data['in_storage_time'];
        $paramsArr['all_id'] = $data['id'];
        isset($data['remark'])?$paramsArr['remark'] = $data['remark']:$paramsArr['remark'] = '';
        $paramsArr['all_id_type'] = 2;//销售退货均为2

        $result = SELF::inStorage($data, $paramsArr);

        return $result;
    }

    static private function inStorage($data, $paramsArr)
    {
        DB::beginTransaction();
        try {

            if($data['status'] == 0) {
                $goodsInfo = json_decode($data['goods_info'], true);
                $packageInfo = json_decode($data['package_info'], true);
            }
            else {
                $goods = json_decode($data['goods_info'], true);
                $package = json_decode($data['package_info'], true);

                $goodsInfo = [];
                $packageInfo = [];
                foreach($goods as $key => $value) {
                    $returnDetail = SalesReturnGoodsDetailModel::selectRaw('
                    price,
                    materiel_type_id,
                    warehouse_id,
                    (num - in_num) as num
                ')
                        ->where([
                            'return_id' => $data['id'],
                            'materiel_type_id' => $value['materiel_type_id']
                        ])->whereRaw('num > in_num')->first();

                    $goodsInfo[] = [
                        'price' => $returnDetail['price'],
                        'materiel_type_id' => $returnDetail['materiel_type_id'],
                        'warehouse_id' => $returnDetail['warehouse_id'],
                        'num' => $returnDetail['num'],
                        'remark' => $value['remark'],
                    ];
                }

                foreach($package as $k => $v) {
                    $packageInfos = SalesReturnPackageModel::selectRaw('
                    id,
                    price,
                    package_id,
                    (num - in_num) as num
                ')
                        ->with('PackageContent')
                        ->where('package_id', $v['package_id'])
                        ->where('return_id', $data['id'])
                        ->whereRaw('num > in_num')->first();

                    $packageInfo[] = [
                        'id' => $packageInfos['id'],
                        'price' => $packageInfos['price'],
                        'package_id' => $packageInfos['package_id'],
                        'num' => $packageInfos['num'],
                        'remark' => $v['remark'],
                        'package_content' => $v['package_content']
                    ];
                }
            }

            if(!empty($goodsInfo)) {
                $paramsArr['content'] = SELF::materielInStorage($paramsArr, $goodsInfo, $data);

                //调用入库
                $res = StorageManageService::inStorage($data['user_id'], $data['main_id'], $paramsArr, $data['batch_title']);
                if($res['code']){
                    return $res;
                }
            }

            if(!empty($packageInfo)) {
                foreach($packageInfo as $k1 => $v1) {
                    //退货单套餐入库记录
                    $salesReturnInPackageInfo = SalesReturnInPackageModel::where([
                        'package_id' => $v1['package_id'],
                        'return_id' => $data['id']
                    ])->first();

                    //退货单套餐信息
                    $salesReturnPackageInfo = SalesReturnPackageModel::where([
                        'package_id' => $v1['package_id'],
                        'return_id' => $data['id']
                    ])->first();

                    $packageInfo1 = PackageModel::where('id', $v1['package_id'])->first();

                    if(!empty($salesReturnInPackageInfo)) {

                        //剩余未入库数量
                        $restPackageNum = $salesReturnPackageInfo['num'] - $salesReturnInPackageInfo['num'];
                        if($restPackageNum < $v1['num']) {
                            return [
                                'code' => 1,
                                'msg' => '套餐:'.$packageInfo1['package_name'].'可入库数量不足,当前可入库数量为:'.$restPackageNum,
                                'data' => ''
                            ];
                        }

                        SalesReturnInPackageModel::where('id', $salesReturnInPackageInfo['id'])
                            ->increment('num', $v1['num'],[
                                'remark' => $v1['remark']
                            ]);

                        SELF::generatePackageLog($salesReturnInPackageInfo, $data, $v1, $packageInfo1);
                    }
                    else {
                        $restNum = $salesReturnPackageInfo['num'] - $salesReturnPackageInfo['in_num'];
                        if($restNum < $v1['num']) {
                            return [
                                'code' => 1,
                                'msg' => '套餐:'.$packageInfo1['package_name'].'可入库数量不足,当前可入库数量为:'.$restNum,
                                'data' => ''
                            ];
                        }

                        SELF::generatePackageLog([], $data, $v1, $packageInfo1);
                    }

                    SalesReturnPackageModel::where([
                        'package_id' => $v1['package_id'],
                        'return_id' => $data['id']
                    ])->increment('in_num', $v1['num']);
                }
            }

            $salesGoodsInfo = SalesReturnGoodsDetailModel::where('return_id', $data['id'])
                ->whereRaw('num > in_num')->get()->toArray();

            $salesPackageInfo = SalesReturnPackageModel::where('return_id', $data['id'])
                ->whereRaw('num > in_num')->get()->toArray();

            if(empty($salesGoodsInfo) && empty($salesPackageInfo)) {
                SalesReturnModel::where('id', $data['id'])->update(['out_status' => 2]);
            }
            else {
                SalesReturnModel::where('id', $data['id'])->update(['out_status' => 1]);
            }

            DB::commit();
            return ['code' => 0, 'msg' => 'success', 'data' => ''];
        }
        catch (\Exception $e) {
            DB::rollBack();
            Log::debug('退货单入库异常:'.var_export($e->getMessage(), true));
            return ['code' => 1, 'msg' => $e->getMessage(), 'data' => ''];
        }
    }

    static private function generatePackageLog($salesReturnInPackageInfo, $data, $v1, $packageInfo)
    {
        DB::enableQueryLog();

        try {
            if (empty($salesReturnInPackageInfo)) {
                $newId = SalesReturnInPackageModel::insert([
                    'package_id' => $v1['package_id'],
                    'num' => $v1['num'],
                    'price' => $v1['price'],
                    'return_id' => $data['id'],
                    'remark' => empty($v1['remark']) ? '' : $v1['remark']
                ]);
            }

            $newLogPackageId = LogPackageModel::insertGetId([
                'package_id' => $v1['package_id'],
                'package_name' => $packageInfo['package_name'],
                'num' => $v1['num'],
                'all_id_type' => 3,
                'all_id' => $data['id'],
                'user_id' => $data['user_id'],
                'main_id' => $data['main_id'],
                'created_at' => time()
            ]);

            foreach ($v1['package_content'] as $k => $v) {
                $storageManageInfo = StorageManageModel::select(
                    'a.id as materiel_type_id',
                    'a.materiel_name',
                    'a.type_name',
                    'a.materiel_no',
                    'b.id as materiel_class_id',
                    'b.class_name',
                    'b.class_no',
                    'c.id as storage_manage_id',
                    'c.in_storage_num',
                    'd.id as storage_id',
                    'd.storage_name',
                    'd.storage_address'
                )
                    ->from('storage_manage as c')
                    ->leftJoin('materiel_type as a', 'a.id', '=', 'c.type_id')
                    ->leftJoin('materiel_class as b', 'b.id', '=', 'c.materiel_class_id')
                    ->leftJoin('storage as d', 'd.id', '=', 'c.storage_id')
                    ->where('c.id', $v['storage_manage_id'])
                    ->first();

                $logPackageContentInfo[] = [
                    'log_package_id' => $newLogPackageId,
                    'package_id' => $v1['package_id'],
                    'storage_id' => $storageManageInfo['storage_id'],
                    'storage_name' => $storageManageInfo['storage_name'],
                    'storage_address' => $storageManageInfo['storage_address'],
                    'materiel_class_id' => $storageManageInfo['materiel_class_id'],
                    'materiel_class_name' => $storageManageInfo['class_name'],
                    'materiel_class_no' => $storageManageInfo['class_no'],
                    'materiel_type_id' => $storageManageInfo['materiel_type_id'],
                    'materiel_name' => $storageManageInfo['materiel_name'],
                    'type_name' => $storageManageInfo['type_name'],
                    'materiel_no' => $storageManageInfo['materiel_no'],
                    'operate_num' => $v1['num'] * $v['num'],
                    'out_storage_manage_id' => $v['storage_manage_id'],
                    'last_storage_num' => $storageManageInfo['in_storage_num'],
                    'next_storage_num' => $storageManageInfo['in_storage_num'] + ($v1['num'] * $v['num']),
                    'all_id_type' => 5,
                    'all_id' => $data['id'],
                    'user_id' => $data['user_id'],
                    'main_id' => $data['main_id'],
                    'created_at' => time()
                ];

                if (empty($salesReturnInPackageInfo)) {
                    SalesReturnInPackageContentModel::insert([
                        'type_id' => $storageManageInfo['materiel_type_id'],
                        'storage_id' => $v['storage_id'],
                        'package_content_id' => $v['id'],
                        'storage_manage_id' => $v['storage_manage_id'],
                        'upper_id' => $newId,
                        'num' => $v['num'],
                        'total_num' => $v1['num'] * $v['num'],
                        'user_id' => $data['user_id'],
                        'main_id' => $data['main_id'],
                        'return_id' => $data['id'],
                        'created_at' => time(),
                    ]);
                }

                StorageManageModel::where('id', $v['storage_manage_id'])
                    ->update([
                        'in_storage_num' => DB::raw('in_storage_num + ' . $v1['num'] * $v['num']),
                        'virtual_storage_num' => DB::raw('virtual_storage_num + ' . $v1['num'] * $v['num']),
                    ]);
            }

            LogPackageContentModel::insert($logPackageContentInfo);
            DB::commit();
            return true;
        } catch (\Exception $e) {
            DB::rollBack();
            Log::debug('退货入库记录及数据同步异常' . var_export($e->getMessage()));
            return ['code' => 1, 'msg' => $e->getMessage(), 'data' => ''];
        }
    }

    static private function materielInStorage($paramsArr, $goodsInfo, $data)
    {
        $info = [];
        foreach($goodsInfo as $value) {
            $salesReturnInStorageInfo = SalesReturnInStorageModel::where([
                'materiel_type_id' => $value['materiel_type_id'],
                'warehouse_id' => $value['warehouse_id'],
                'return_id'=>$data['id'],
            ])
                ->first();

            $salesReturnGoodsDetailInfo = SalesReturnGoodsDetailModel::where([
                'materiel_type_id'=>$value['materiel_type_id'],
                'return_id'=>$data['id']
            ])
                ->first();

            $materielInfo = MaterielTypeModel::where('id', $value['materiel_type_id'])->first();
            $storageInfo = StorageModel::where('id', $value['warehouse_id'])->first();

            if(empty($salesReturnInStorageInfo)) {
                if($value['num'] > $salesReturnGoodsDetailInfo['num']) {
                    throw new \Exception('超出可入库数量，当前可操作数量为:'.$salesReturnGoodsDetailInfo['num']);
                }

                SalesReturnInStorageModel::insert([
                    'materiel_type_id' => $value['materiel_type_id'],
                    'name' => $materielInfo['materiel_name'],
                    'type_name' => $materielInfo['type_name'],
                    'warehouse' => $storageInfo['storage_name'],
                    'warehouse_id' => $storageInfo['id'],
                    'num' => $value['num'],
                    'return_id' => $data['id'],
                    'remark' => empty($value['remark'])?'':$value['remark'],
                ]);
            }
            else {
                if($value['num'] > ($salesReturnGoodsDetailInfo['num'] - $salesReturnGoodsDetailInfo['in_num'])) {
                    throw new \Exception('超出可入库数量，当前可操作数量为:'.$salesReturnGoodsDetailInfo['num']);
                }

                SalesReturnInStorageModel::where(['materiel_type_id'=>$value['materiel_type_id'],'return_id'=>$data['id']])
                    ->increment('num', $value['num'], [
                        'remark' => empty($value['remark'])?'':$value['remark']
                    ]);
            }

            SalesReturnGoodsDetailModel::where([
                'materiel_type_id' => $value['materiel_type_id'],
                'warehouse_id' => $value['warehouse_id'],
                'return_id' => $data['id']
            ])->increment('in_num', $value['num']);

            $info[] = [
                'name' => $materielInfo['materiel_name'],
                'type_name' => $materielInfo['type_name'],
                'num' => $value['num'],
                'warehouse' => $storageInfo['storage_name'],
                'warehouse_id' => $storageInfo['id'],
            ];
        }

        return $info;
    }

    static private function materielInStorage1($paramsArr, $goodsInfo, $data)
    {
        foreach($goodsInfo as $key => $value) {
            $salesReturnInStorageInfo = SalesReturnInStorageModel::where(['materiel_type_id'=>$value['materiel_type_id'],'return_id'=>$data['id']])->first();
            $salesReturnGoodsDetailInfo = SalesReturnGoodsDetailModel::where(['materiel_type_id'=>$value['materiel_type_id'],'return_id'=>$data['id']])->first();//原始入库数量

            $materielInfo = MaterielTypeModel::where('id', $value['materiel_type_id'])->first();
            $storageInfo = StorageModel::where('id', $value['warehouse_id'])->first();

            if(empty($salesReturnInStorageInfo)) {
                if(!($value['num'] <= $salesReturnGoodsDetailInfo['num'])) {
                    return ['code' => 1, 'msg' => '超出可入库数量，当前可操作数量为:'.$salesReturnGoodsDetailInfo['num'], 'data' => ''];
                }

                $arr = [
                    'materiel_type_id' => $value['materiel_type_id'],
                    'name' => $materielInfo['materiel_name'],
                    'type_name' => $materielInfo['type_name'],
                    'warehouse' => $storageInfo['storage_name'],
                    'warehouse_id' => $storageInfo['id'],
                    'num' => $value['num'],
                    'return_id' => $data['id'],
                    'remark' => empty($value['remark'])?'':$value['remark'],
                ];
                SalesReturnInStorageModel::insert($arr);
            }
            else {
                if($value['num'] > ($salesReturnGoodsDetailInfo['num'] - $salesReturnGoodsDetailInfo['in_num'])){
                    return ['code' => 1, 'msg' => '超出可入库数量，当前可操作数量为:'.($salesReturnGoodsDetailInfo['num'] - $salesReturnGoodsDetailInfo['in_num']), 'data' => ''];
                }

                SalesReturnInStorageModel::where(['materiel_type_id'=>$value['materiel_type_id'],'return_id'=>$data['id']])
                    ->increment('num', $value['num'], [
                        'remark' => empty($value['remark'])?'':$value['remark']
                    ]);
            }

            SalesReturnGoodsDetailModel::where([
                'materiel_type_id' => $value['materiel_type_id'],
                'return_id' => $data['id']
            ])->increment('in_num', $value['num']);

            $paramsArr['content'][$key]['name'] = $materielInfo['materiel_name'];
            $paramsArr['content'][$key]['type_name'] = $materielInfo['type_name'];
            $paramsArr['content'][$key]['num'] = $value['num'];
            $paramsArr['content'][$key]['warehouse'] = $storageInfo['storage_name'];
            $paramsArr['content'][$key]['warehouse_id'] = $storageInfo['id'];
        }

        return $paramsArr;
    }

    static public function list($userId, $data)
    {
        if(!empty($data['keyword'])) {//关键词搜索组是否启用
            $result = self::withKeyword($userId, $data);
        }
        else {
            $result = SELF::withoutKeyword($userId, $data);
        }

        return $result;
    }

    //列表检索-有关键词
    static private function withKeyword($userId, $data)
    {
        switch($data['search_type']) {
            //1->商品名称;2->商品编号
            case 1:
            case 2:
                $result = SELF::searchGoodsInfo($userId, $data);
                break;
            //内部单号
            case 3:
                $result = SELF::searchInnerOrderNo($userId, $data);
                break;
            //外部单号
            case 4:
                $result = SELF::searchOutOrderNo($userId, $data);
                break;
            //快递单号
//            case 5:
//                $result = SELF::searchKuaidiNo($userId, $data);
//                break;
            //客户名称
            case 6:
                $result = SELF::searchCustomer($userId, $data);
                break;
            //司机名城
//            case 7:
//                $result = SELF::searchInnerOrderNo($userId, $data);
//                break;
            //收货人
            case 8:
                $result = SELF::searchConsignee($userId, $data);
                break;
        }

        return $result;
    }

    //列表-客户名称
    static public function searchConsignee($userId, $data)
    {
        $condition[] = ['consignee', 'like', '%'.$data['keyword'].'%'];
        $salesInfo = SalesReturnModel::getSalesIdInfo($userId, $data, $condition);

        $salesId = [];
        foreach($salesInfo as $value) {
            $salesId[] = $value['id'];
        }

        return SELF::commonSearchWithKeyword($userId, $data, $salesId);
    }

    //列表-客户名称
    static public function searchCustomer($userId, $data)
    {
        $condition[] = ['customer_name', 'like', '%'.$data['keyword'].'%'];
        $salesInfo = SalesReturnModel::getSalesIdInfo($userId, $data, $condition);

        $salesId = [];
        foreach($salesInfo as $value) {
            $salesId[] = $value['id'];
        }

        return SELF::commonSearchWithKeyword($userId, $data, $salesId);
    }

    //列表-快递单号搜索
//    static public function searchKuaidiNo($userId, $data)
//    {
//        $condition[] = ['order_no', 'like', '%'.$data['keyword'].'%'];
//        $salesInfo = SalesReturnModel::getSalesIdInfo($userId, $data, $condition);
//
//        $salesId = [];
//        foreach($salesInfo as $value) {
//            $salesId[] = $value['id'];
//        }
//
//        return SELF::commonSearchWithKeyword($userId, $data, $salesId);
//    }

    static private function searchOutOrderNo($userId, $data)
    {
        $condition[] = ['out_order_no', 'like', '%'.$data['keyword'].'%'];
        $salesInfo = SalesReturnModel::getSalesIdInfo($userId, $data, $condition);

        $salesId = [];
        foreach($salesInfo as $value) {
            $salesId[] = $value['id'];
        }

        return SELF::commonSearchWithKeyword($userId, $data, $salesId);
    }

    static private function searchInnerOrderNo($userId, $data)
    {
        $condition[] = ['order_no', 'like', '%'.$data['keyword'].'%'];
        $salesInfo = SalesReturnModel::getSalesIdInfo($userId, $data, $condition);

        $salesId = [];
        foreach($salesInfo as $value) {
            $salesId[] = $value['id'];
        }

        return SELF::commonSearchWithKeyword($userId, $data, $salesId);
    }

    static private function searchGoodsInfo($userId, $data)
    {
        $salesInfo = SalesReturnModel::select('id')->where($userId)
            ->where('repeal_status', $data['repeal_status'])
            ->from('sales_return as a')
            ->get()->toArray();

        $salesId = [];
        foreach($salesInfo as $value) {
            $salesId[] = $value['id'];
        }

        $condition = [];
        $condition1 = [];
        if($data['search_type'] == 1) {
            $condition[] = ['b.materiel_name', 'like', '%'.$data['keyword'].'%'];
            $condition1[] = ['materiel_name', 'like', '%'.$data['keyword'].'%'];
        }
        else if($data['search_type'] == 2) {
            $condition[] = ['b.materiel_no', 'like', '%'.$data['keyword'].'%'];
            $condition1[] = ['materiel_no', 'like', '%'.$data['keyword'].'%'];
        }

        $goodsDetailInfo = SalesReturnGoodsDetailModel::getGoodsDetailInfo($salesId, $condition);
        $packageContentInfo = SalesReturnPackageContentModel::getPackageContentInfo($salesId, $condition1);

        $salesIdArr = [];
        foreach($goodsDetailInfo as $value) {
            $salesIdArr[] = $value['return_id'];
        }

        //获取商品信息和套餐内商品信息的销售单id集合
        foreach($packageContentInfo as $val) {
            if(!in_array($val['return_id'], $salesIdArr)) {
                array_push($salesIdArr, $val['return_id']);
            }
        }

        return SELF::commonSearchWithKeyword($userId, $data, $salesIdArr);
    }

    //使用关键词检索-公共方法
    static private function commonSearchWithKeyword($userId, $data, $salesIdArr)
    {
        $query = SalesReturnModel::select(
            'a.*',
            'b.username',
            'b.nickname'
        )
        ->from('sales_return as a')
        ->leftJoin('admin as b', 'b.id', '=', 'a.user_id')
        ->with('returnMateriel', function($query) {
            $query->select(
                'sales_return_goods_detail.id',
                'a.materiel_name as name',
                'a.type_name',
                'a.materiel_no',
                'a.materiel_img as image',
                'price',
                'sales_return_goods_detail.num',
                'sales_return_goods_detail.in_num',
                'b.storage_name as warehouse',
                'b.id as warehouse_id',
                'sales_return_goods_detail.materiel_type_id',
                'sales_return_goods_detail.return_id',
                'cost_price',
                'return_id'
            )->leftJoin('materiel_type as a', 'a.id', '=', 'sales_return_goods_detail.materiel_type_id')
                ->leftJoin('storage as b', 'b.id', '=', 'sales_return_goods_detail.warehouse_id');
        })
            ->with('returnPackage', function($query) {
                $query->select(
                    'sales_return_package.id',
                    'b.package_name',
                    'sales_return_package.price',
                    'sales_return_package.cost_price',
                    'sales_return_package.num',
                    'in_num',
                    'sales_return_package.return_id'
                )
                    ->leftJoin('package as b', 'b.id', '=', 'sales_return_package.package_id')
                    ->with('PackageContent', function($query) {
                        $query->select(
                            'sales_return_package_content.id',
                            'sales_return_package_content.type_id',
                            'a.materiel_name',
                            'a.type_name',
                            'a.materiel_no',
                            'a.materiel_img',
                            'b.id as materiel_class_id',
                            'b.class_name',
                            'sales_return_package_content.storage_id',
                            'sales_return_package_content.num',
                            'return_package_id',
                            'sales_return_package_content.storage_manage_id',
                            'd.storage_name',
                            'd.storage_address'
                        )
                            ->leftJoin('materiel_type as a', 'a.id', '=', 'sales_return_package_content.type_id')
                            ->leftJoin('materiel_class as b', 'b.id', '=', 'a.materiel_class_id')
                            ->leftJoin('storage_manage as c', 'c.id', '=', 'sales_return_package_content.storage_manage_id')
                            ->leftJoin('storage as d', 'd.id', '=', 'c.storage_id');
                    });
            })
            ->where($userId)
            ->where([
                'repeal_status' => $data['repeal_status'],
                'a.delete_flag' => 0
            ]);

        if(!empty($data['start_time'])) {
            $startTimeArr = explode(' ', $data['start_time']);
            $startTime = strtotime($startTimeArr[0].' 00:00:00');
        }

        if(!empty($data['end_time'])) {
            $endTimeArr = explode(' ', $data['end_time']);
            $endTime = strtotime($endTimeArr[0].' 23:59:59');
        }

        if(!empty($startTime) && !empty($endTime)) {
            $query->whereBetween('refund_date', [$startTime, $endTime]);
        }
        else if(!empty($startTime) && empty($endTime)) {
            $query->where('refund_date', '>=', $startTime);
        }
        else if(empty($startTime) && !empty($endTime)) {
            $query->where('refund_date', '<=', $endTime);
        }

        //销售单状态
        switch($data['status']) {
            case 1://新订单
                $query->where('out_status', 0);
                $query->where('pay_status', 0);
                break;
            case 2://待退款(已收货)
                $query->where('pay_status', 0);
                $query->whereIn('out_status', [1,2]);
                break;
            case 3://待退款(已收货)
                $query->where('out_status', 0);
                $query->whereIn('pay_status', [1,2]);
                break;
            case 4:
                $query->where('out_status', 2);
                $query->where('pay_status', 2);
                break;
        }
        $query->whereIn('a.id', $salesIdArr);

        $query = $query->orderBy('a.id','desc')
            ->paginate($data['pageSize'],['*'], '',$data['currentPage'])->toArray();

        foreach($query['data'] as &$value) {
            foreach($value['return_materiel'] as $k => $val) {
                $storageManageInfo = StorageManageModel::where('type_id', $val['materiel_type_id'])
                    ->where('storage_id', $val['warehouse_id'])->first();

                $value['return_materiel'][$k]['in_storage_num'] = $storageManageInfo['in_storage_num'];
            }
        }

        return $query;
    }

    //列表检索-无关键词
    static private function withoutKeyword($userId, $data)
    {
        $query = SalesReturnModel::select(
            'a.*',
            'b.username',
            'b.nickname'
        )
            ->from('sales_return as a')
            ->leftJoin('admin as b', 'b.id', '=', 'a.user_id')
            ->with('returnMateriel', function($query) {
                $query->select(
                    'sales_return_goods_detail.id',
                    'a.materiel_name as name',
                    'a.type_name',
                    'a.materiel_no',
                    'a.materiel_img as image',
                    'price',
                    'sales_return_goods_detail.num',
                    'sales_return_goods_detail.in_num',
                    'b.storage_name as warehouse',
                    'b.id as warehouse_id',
                    'sales_return_goods_detail.materiel_type_id',
                    'sales_return_goods_detail.return_id',
                    'cost_price',
                    'return_id'
                )->leftJoin('materiel_type as a', 'a.id', '=', 'sales_return_goods_detail.materiel_type_id')
                    ->leftJoin('storage as b', 'b.id', '=', 'sales_return_goods_detail.warehouse_id');
            })
            ->with('returnPackage', function($query) {
                $query->select(
                    'sales_return_package.id',
                    'b.package_name',
                    'sales_return_package.price',
                    'sales_return_package.cost_price',
                    'sales_return_package.num',
                    'in_num',
                    'sales_return_package.return_id'
                )
                    ->leftJoin('package as b', 'b.id', '=', 'sales_return_package.package_id')
                    ->with('PackageContent', function($query) {
                        $query->select(
                            'sales_return_package_content.id',
                            'sales_return_package_content.type_id',
                            'a.materiel_name',
                            'a.type_name',
                            'a.materiel_no',
                            'a.materiel_img',
                            'b.id as materiel_class_id',
                            'b.class_name',
                            'sales_return_package_content.storage_id',
                            'sales_return_package_content.num',
                            'sales_return_package_content.storage_manage_id',
                            'return_package_id',
                            'd.storage_name',
                            'd.storage_address'
                        )
                            ->leftJoin('materiel_type as a', 'a.id', '=', 'sales_return_package_content.type_id')
                            ->leftJoin('materiel_class as b', 'b.id', '=', 'a.materiel_class_id')
                            ->leftJoin('storage_manage as c', 'c.id', '=', 'sales_return_package_content.storage_manage_id')
                            ->leftJoin('storage as d', 'd.id', '=', 'c.storage_id');
                    });
            })
            ->where($userId)
            ->where([
                'repeal_status' => $data['repeal_status'],
                'a.delete_flag' => 0
            ]);
        if(!empty($data['start_time'])) {
            $startTimeArr = explode(' ', $data['start_time']);
            $startTime = strtotime($startTimeArr[0].' 00:00:00');
        }

        if(!empty($data['end_time'])) {
            $endTimeArr = explode(' ', $data['end_time']);
            $endTime = strtotime($endTimeArr[0].' 23:59:59');
        }

        if(!empty($startTime) && !empty($endTime)) {
            $query->whereBetween('refund_date', [$startTime, $endTime]);
        }
        else if(!empty($startTime) && empty($endTime)) {
            $query->where('refund_date', '>=', $startTime);
        }
        else if(empty($startTime) && !empty($endTime)) {
            $query->where('refund_date', '<=', $endTime);
        }

        //销售单状态
        switch($data['status']) {
            case 1://新订单
                $query->where('out_status', 0);
                $query->where('pay_status', 0);
                break;
            case 2://待退款(已收货)
                $query->where('pay_status', 0);
                $query->whereIn('out_status', [1,2]);
                break;
            case 3://待退款(已收货)
                $query->where('out_status', 0);
                $query->whereIn('pay_status', [1,2]);
                break;
            case 4:
                $query->where('out_status', 2);
                $query->where('pay_status', 2);
                break;
        }

        $query = $query->orderBy('id','desc')
        ->paginate($data['pageSize'],['*'], '',$data['currentPage'])->toArray();

        foreach($query['data'] as &$value) {
            foreach($value['return_materiel'] as $k => $val) {
                $storageManageInfo = StorageManageModel::where('type_id', $val['materiel_type_id'])
                    ->where('storage_id', $val['warehouse_id'])->first();

                $value['return_materiel'][$k]['in_storage_num'] = $storageManageInfo['in_storage_num'];
            }
        }

        return $query;
    }

    static public function payHistory($id)
    {
        if(empty(SalesReturnPayRecordModel::where('return_id', $id)->first())) {
            return '';
        }
        else {
            return SalesReturnPayRecordModel::select(
                'a.order_no',
                'b.*'
            )
                ->from('sales_return as a')
                ->leftJoin('sales_return_pay_record as b', 'a.id', '=', 'b.return_id')
                ->where('a.id', $id)
                ->get()->toArray();
        }
    }
}
